const express = require("express")
const router = express.Router()
const path = require("path")

const multer = require("multer");



// 保存文件的格式
// 调用插件中的磁盘存储引擎
const storage = multer.diskStorage({
    destination : function(req,file,cb){//文件存储在服务端地址
        cb(null,path.resolve(__dirname,"../../public","upload"))
    },
    filename : function(req,file,cb){
        // 时间戳+随机字符6位+文件后缀名
        const timeStamp = Date.now()
        const ramdomStr = Math.random().toString(36).slice(-6)
        const ext = path.extname(file.originalname)
        const filename = `${timeStamp}-${ramdomStr}${ext}`
        cb(null,filename)
    }
})
const upload =  multer({
    storage 
})
router.post("/",upload.single("img"),(req,res)=>{
    res.send({
        code : 0,
        msg : '',
        data : `/upload/${req.file.filename}`
    })

})
router.post("/img",upload.single("img"),(req,res)=>{
    res.send({
        "errno": 0, // 注意：值是数字，不能是字符串
        "data": {
            "url":`/upload/${req.file.filename}`, // 图片 src ，必须
        }
    })
})


module.exports = router;